<!--
 * @Author: 计都 3038199036@qq.com
 * @Date: 2024-09-24 15:41:38
 * @LastEditors: 计都 3038199036@qq.com
 * @LastEditTime: 2024-10-12 15:25:10
 * @FilePath: \express_file_upload-master\views\upload.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>文件上传</title>
  <link rel="icon" type="image/x-icon" href="favicon.ico" />
  <style>
    @font-face {
      font-family: "baseFont";
      src: url("/static/font/OPPOSans-B-2.ttf");
    }

    * {
      font-family: "baseFont";
      font-weight: bolder;
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      text-decoration: none;
      word-wrap: break-word;
      word-break: keep-all;
    }

    h4 {
      background-color: #414181;
      color: white;
      text-indent: 20px;
      padding: 10px;
      margin: 10px;
      border-radius: 1rem;
    }

    #submit {
      position: relative;
      /* right: 10px; */
      left: calc(100% - 90px);
      border: none;
      margin-top: 10px;
      border-radius: 1rem;
      background-color: #414181;
      color: white;
      padding: 3px 15px;
      font-weight: 500;
      cursor: pointer;
    }

    #submit:active {
      background-color: white;
      color: #414181;
    }

    .bg_container {
      position: fixed;
      top: 0;
      left: 0;
      z-index: -999;
      width: 100vw;
      height: 100vh;
      background: linear-gradient(45deg,
          #3498db,
          #2ecc71);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }

    .bg_container::before {
      content: "";
      position: fixed;
      top: 0;
      left: 0;
      z-index: -999;
      width: 100vw;
      height: 100vh;
      background-image: linear-gradient(90deg,
          rgba(255, 255, 255, 0.1) 1px,
          transparent 1px),
        linear-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 1px);
      background-size: 20px 20px;
      pointer-events: none;
      /* Allow clicking through the pattern layer */
    }

    .root,
    .section {
      position: relative;
      margin: 10px;
      background-color: #d6d6e5c5;
      color: #414181;
      padding: 10px 10px 10px 40px;
      margin: 0 10px 10px 10px;
      border-radius: 1rem;
    }

    .section {
      display: flex;
      flex-wrap: nowrap;
      justify-content: left;
      align-items: center;
      padding: 5px;
      gap: 10px;
    }

    .section>a {
      font-size: 12px;
      background-color: #414181;
      border-radius: 1rem;
      padding: 5px 20px 5px 20px;
      color: white;
      border: 1px solid #414181;
      transition: all .3s cubic-bezier(0, 0, 0, 1);
    }

    .section>a:hover {
      background-color: #d6d6e5;
      color: #414181;
    }

    /* 
      #uploadForm {
        border-bottom: 1px solid white;
      } */

    #file {
      padding: 0 10px 0 0;
      border: 3px solid white;
      border-radius: 1rem;
      width: 100px;
    }

    ::file-selector-button {
      cursor: pointer;
      border: none;
      background-color: #414181;
      color: white;
      font-weight: bolder;
      margin: 3px;
      border-radius: 1rem;
      width: 100px;
    }

    .rootSafe {
      position: relative;
      margin: 10px;
      background-color: #d6d6e5c5;
      color: #414181;
      padding: 10px;
      margin: 0 10px 10px 10px;
      border-radius: 1rem;
    }

    .title {
      width: 100%;
      text-align: center;
      line-height: 30px;
      background-color: #414181;
      color: #fff;
      letter-spacing: 1px;
      font-size: 16px;
      border-radius: 1rem;
    }

    .code-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      margin: 10px auto;
      position: relative;
      /* border-top: 3px solid white;
      border-bottom: 3px solid white; */
    }

    .code-box .code-item {
      width: 7vw;
      height: 7vw;
      overflow: hidden;
      background-color: #fff;
      border-radius: .5rem;
      text-align: center;
      line-height: 7vw;
      font-size: 4vw;
      color: #414181;
      font-weight: bolder;
      border: 1px solid #41418180;
      transition: all 0.5s cubic-bezier(0, 0, 0, 1);
      box-sizing: border-box;
    }

    .code-box .code-input {
      position: absolute;
      width: 100%;
      height: 100%;
      opacity: 0;
    }

    .active {
      border: 3px solid #414181 !important;
    }

    .btn_container {
      display: flex;
      flex-direction: row-reverse;
      gap: 10px;
    }

    .btn_container button {
      border: 1px solid #414181;
      border-radius: 1rem;
      background-color: #414181;
      color: white;
      height: 22px;
      width: 60px;
      font-size: 14px;
      font-weight: 300;
      transition: all 0.3s cubic-bezier(0, 0, 0, 1);
      cursor: pointer;
    }

    .btn_container button:active {
      background-color: white;
      color: #414181;
    }
  </style>
</head>

<body>
  <h4>文件上传</h4>
  <div class="section">
    <a href="/filelist">文件列表</a>
    <a href="/handleFile">文件归档</a>
    <span id="checkSafety">安全检查未通过</span>
  </div>
  <div class="rootSafe">

    <div class="title">安全检查</div>
    <div class="code-box">
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <div class="code-item"></div>
      <input type="text" class="code-input" maxlength="12" placeholder="" title="验证码" id="securityCheck"
        oninput="value=value.replace(/[^\d]/g,'')">
    </div>
    <div class="btn_container">
      <button id="confirm">确认</button>
      <button id="cancel">清空</button>
    </div>
  </div>
  <div class="root">
    <form id="uploadForm" action="" method="post" enctype="multipart/form-data">
      <label for="file">选择文件上传:</label>
      <input type="file" name="file" multiple="multiple" title="file" id="file"
        style="overflow: hidden;width: calc(100% - 30px) ">
      <input type="submit" value="提交" id="submit"><br><br>
    </form>
  </div>
  <div class="bg_container"></div>
</body>

<script src="/static/jquery.js"></script>
<script>
  // 选择所有class为code - item的元素
  const codeItems = document.querySelectorAll('.code-item');
  // 对每个元素独立设置观察器
  codeItems.forEach((codeItem) => {
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        // 检查是否是文本节点变化并且有非空字符
        if (mutation.target.textContent.trim() !== '') {
          codeItem.style.height = '0';
        } else {
          codeItem.style.height = '7vw';
        }
      });
    });

    const config = {
      childList: true,
      characterData: true,
      subtree: true
    };
    observer.observe(codeItem, config);
  });
  $(document).ready(function () {
    const $lastCodeItem = $('.code-item:last');
    const observer = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
          const height = parseInt($lastCodeItem.css('height'));
          if (height < 30) {
            $('.btn_container button').css({ 'width': '60px', 'height': '22px', 'font-size': '14px' });
          } else {
            $('.btn_container button').css({ 'width': '80px', 'height': '26px', 'font-size': '16px' });
          }
        }
      });
    });

    observer.observe($lastCodeItem[0], { attributes: true });
  });
  $(function () {
    if (sessionStorage.getItem('token') !== '') {
      $.ajax({
        type: 'POST',
        url: '/stats',
        headers: {
          Authorization: 'Bearer ' + sessionStorage.getItem('token')
        },
        success: function (response) {
          console.log(response.SS);
          if (response.SS) {
            $('.btn_container').hide();
            $('.code-box').hide();
            $('.title').text('安全检查已通过✔️');
            $('#checkSafety').text('');
          }
        },
      })
    }
  })
  $(function () {
    $('#confirm').click(function () {
      // console.log($('#securityCheck').val());
      if ($('#securityCheck').val() === "200209239029") {
        $.ajax({
          url: '/safety', // 替换为你的后端接口地址
          type: 'POST',
          success: function (response) {
            // 将获取到的 token 存储在浏览器中
            sessionStorage.setItem('token', response.token); // 或使用 sessionStorage
            console.log('Token stored successfully:', response.token);
            window.location.reload();
          },
          error: function (error) {
            console.error('Error fetching token:', error);
          }
        });
      } else if ($('#securityCheck').val().length != 12) {
        alert("请输入完整的校验码");
      } else {
        alert("校验码错误，请重新输入！");
        window.location.reload();
      };
    });
    // 提交表单
    $("#submit").click(function (event) {
      // 阻止表单默认提交
      event.preventDefault();
      $.ajax({
        type: 'POST',
        url: '/upload',
        processData: false,
        contentType: false,
        data: new FormData($("#uploadForm")[0]), headers: {
          Authorization: 'Bearer ' + sessionStorage.getItem('token')
        },
        success: function (data) {
          alert('上传成功！')
          window.location.reload();
        },
        error: function (xhr, status, error) {
          console.error('未通过安全检查：', error);
          alert('未通过安全检查');
        }
      })
    })
  })
  window.addEventListener('load', () => {
    // 获取元素
    const codeItem = document.querySelectorAll('.code-item')
    const codeInput = document.querySelector('.code-input')

    // 循环显示input中的值到code-item中
    const showNum = () => {
      // 获取到当前input的值
      const curVal = codeInput.value
      // 循环显示到code-item中
      Array.from(codeItem).map((item, index) => {
        curVal[index] ?
          item.innerText = curVal[index] :
          item.innerText = ''
      })
    }

    // 处理active类的增删
    const cutAct = (type) => {
      // 获取当前input中值的长度
      const valLenth = codeInput.value.length
      // 首先清除之前的active类名
      Array.from(codeItem).map(item => {
        item.className = 'code-item'
      })
      // 当type为focus时 进行计算active位置 否则只清除
      if (type === 'focus') {
        // 计算出当前应该active的code-item 并且给他添加active类名
        codeItem[valLenth === 12 ? valLenth - 1 : valLenth].className = 'code-item active'
      }
    }

    // 为输入框添加事件
    codeInput.addEventListener('focus', () => {
      // 聚焦时 计算active的code-item
      cutAct('focus')
    })

    codeInput.addEventListener('blur', () => {
      // 失去焦点时 移除当前的active
      cutAct('blur')
    })

    codeInput.addEventListener('input', () => {
      // 当输入值时，调用循环显示函数
      showNum()
      cutAct('focus')
    })

    $('#cancel').click(function () {
      $('#securityCheck').val("");
      showNum()
    });
  })
</script>

</html>